package 并发编程15.线程工厂;

import 并发编程15.Demo;

import java.util.concurrent.*;

/**
 * 关于线程工厂的设置学习
 *
 * @author idea
 * @data 2019/2/6
 */
public class MyThreadFactory implements ThreadFactory {

    private int numbers=0;

    /**
     * 可以在创建线程的时候设置异常的处理，线程名称，计数，属性信息等
     *
     * @param r
     * @return
     */
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println(t.getName() + ":" + e.getMessage().toString());
            }
        });
        //设置是否属于守护线程
        thread.setDaemon(false);
        //设置优先级
//        thread.setPriority(1);
        //记录线程个数
        numbers++;
        thread.setName("Thread-idea-"+System.currentTimeMillis());
        return thread;
    }


    public static void main(String[] args) {
        MyThreadFactory myThreadFactory=new MyThreadFactory();
        Demo demo=new Demo();
        ThreadPoolExecutor threadPoolExecutor=
                new ThreadPoolExecutor(1,2,1,TimeUnit.SECONDS,new LinkedBlockingQueue(),myThreadFactory,new ThreadPoolExecutor.AbortPolicy());
        for(int i=0;i<100;i++){
            threadPoolExecutor.execute(demo);
            System.out.println(threadPoolExecutor.getQueue().size());
        }
        threadPoolExecutor.shutdown();
    }
}
